import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormControl, FormGroup} from '@angular/forms';
import {Http} from '@angular/http';
import {ActivatedRoute, ParamMap, Router} from '@angular/router';
import {CamType} from "../../shared/model/camType";
import {CamTypeService} from "../../shared/service/cam-type.service";

@Component({
  selector: 'app-type-edit-form',
  templateUrl: './type-edit-form.component.html',
  styleUrls: ['./type-edit-form.component.css']
})
export class TypeEditFormComponent implements OnInit {
  typeForm: FormGroup;
  oid: string;
  type:CamType;
  constructor(private fb: FormBuilder,
              private http: Http,
              private routeInfo: ActivatedRoute,
              private camTypeService:CamTypeService,
              private router:Router) {
    this.createForm();
  }

  ngOnInit() {
    this.routeInfo.paramMap
      .switchMap((params: ParamMap) => this.camTypeService.getTypeByOid(this.routeInfo.snapshot.params["oidByType"]))
      .subscribe(type => {
        this.type = type;
        this.typeForm.reset({
          oid:this.type.oid,
          id:this.type.id,
          name:this.type.name,
          description:this.type.description
        });
      });
  }
  onSubmit(val:any){
    let msg ="";
    if(!this.typeForm.get("id").value.replace(/^\s+|\s+$/g,"")){
      msg +=("请输入类型代号\n");
    }
    if(!this.typeForm.get("name").value.replace(/^\s+|\s+$/g,"")){
      msg +=("请输入类型名称\n");
    }

    if(msg){
      alert(msg);
    }else{
      this.camTypeService.updateType(this.typeForm.value).then(res => {
        //状态码1为成功
        if (res.code === 1) {
          alert(res.message);
          this.camTypeService.listFreshEvent.emit("edit");
          this.router.navigateByUrl('camType/new');
        } else {
          alert(res.message);
        }
      })
    }
  }

  toSearchId(){

  }
  createForm(){
    this.typeForm =this.fb.group({
      oid:'',
      id:new FormControl({value: '', disabled: true}),
      name: "",
      description: ""
    });
  }

  updateInfo(val:any){
    let msg ="";
    if(!this.typeForm.get("id").value.replace(/^\s+|\s+$/g,"")){
      msg +=("请输入类型代号\n");
    }
    if(!this.typeForm.get("name").value.replace(/^\s+|\s+$/g,"")){
      msg +=("请输入类型名称\n");
    }

    if(msg){
      alert(msg);
    }else{
      this.camTypeService.updateType(this.typeForm.value).then(res => {
        //状态码1为成功
        if (res.code === 1) {
          alert(res.message);
          this.camTypeService.listFreshEvent.emit("edit");
          this.router.navigateByUrl('camType/new');
        } else {
          alert(res.message);
        }
      })
    }
  }
}
